#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());

        int SUM = 0x3f3f3f;
        int cur, l , r;
        int res = 0;
        for (int i = 0; i < nums.size(); i ++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            // 找到最接近 target-nums[i]的a + b。 c = nums[i]
            l = i + 1;
            r = nums.size() - 1;
            while (l < r) {
                cur = nums[i] + nums[l] + nums[r];
                // cout << nums[i] << " " << nums[l] << " " << nums[r] << endl;

                if (cur < target) {
                    l++;
                } else if (cur > target) {
                    r--;
                } else {
                    return target;
                }

                if (SUM > abs(target - cur)) {
                    SUM = abs(target - cur);
                    res = cur;
                }
            }
        } 

        return res;
    }
};